import React, { useEffect, useState } from 'react'
import { message, Modal, notification, Spin } from 'antd'
import useGetTableData from '@/hooks/useGetTableDataV2'
import { getPageOtbList, purchaseOtbAuditOtb, importPurchaseOtb } from '@/api/goods'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useColumns } from './TableColumns'
import { ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import { useNavigate } from 'react-router-dom'
import { ExclamationCircleOutlined, ImportOutlined } from '@ant-design/icons'
import { getProductClassConfigByType } from '@/api/goods'
import PermissionButton from '@/components/PermissionButton'
import { useAppSelector } from '@/store/hooks'
import { searchConfig } from './FormConfig'
import { importNotification } from '@/utils/util'
import useCachePage from '@/hooks/useCachePage'
import { IMPORT_FILE_ENUM, OperationLogType } from '@/constant'
import useViewLogs from '@/hooks/useViewLogs'
import LogsDrawer from '@/components/LogsDrawer'
import ImportFileModal from '@/components/ImportFileModal'
import './index.less'
const Index: React.FC = () => {
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [form] = useForm()
  const [FormUpload] = useForm()
  const [exportLoading, setexportLoading] = useState(false)
  const [isUploadFileShow, setisUploadFileShow] = useState<boolean>(false)
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [spinning, setspinning] = useState(false)
  const { setCachePage, getCachePage } = useCachePage()
  // 日志
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'id',
    OperationLogType.PURCHASE_OTB,
  )
  const { tableProps, params, search, reset, reload } = useGetTableData<ITableData>(getPageOtbList, {
    form: form,
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
    paramsCallback: (reqParams) => {
      return {
        ...reqParams,
      }
    },
  })
  useEffect(() => {
    getProductClassConfig()
    handleCacheData()
  }, [])
  const onUploadFileCancel = () => {
    FormUpload.resetFields()
    setisUploadFileShow(false)
  }
  const handleCacheData = async () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      await form.validateFields()
      search()
      setCachePage({ ...params })
    } else {
      form.resetFields()
      form.setFieldsValue({
        ...cacheData,
      })
      reload({ ...cacheData })
    }
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
          isLeaf: false,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  const verifyCost = (info: ITableData) => {
    if (Number(info.auditCostAmount) < Number(info.usedCostAmount)) {
      message.warning('待审核额度小于已用额度！')
      return
    }
    const instance = Modal.confirm({
      title: '提示',
      content: '是否确认审核额度?',
      okText: '确认',
      cancelText: '取消',
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        const res = await purchaseOtbAuditOtb({
          ...info,
        }).finally(() => {
          instance.destroy()
        })
        if (res.code === 200) {
          reload()
          message.success('操作成功')
        }
        if (res.code === 820000) {
          notification.open({
            type: 'warning',
            message: res?.msg,
          })
        }
      },
    })
  }
  const onViewLogs = (info: ITableData) => {
    viewLogs(info)
  }
  const onUploadFileOk = async () => {
    const { file } = await FormUpload.validateFields()
    setexportLoading(true)
    const res = await importPurchaseOtb<{ linkUrl: string }>(file).finally(() => {
      setexportLoading(false)
      FormUpload.resetFields()
    })
    if (res.code === 200) {
      importNotification(res?.data?.linkUrl)
      search()
      onUploadFileCancel()
    }
  }
  return (
    <PageContainer className="goods_otblimit_wrap">
      <SearchForm
        params={params}
        form={form}
        searchConfig={searchConfig({
          DICTDATA,
          classBig,
        })}
        onFinish={async () => {
          search()
          setCachePage({
            ...form.getFieldsValue(),
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          reset()
          setCachePage({ current: 1, size: 10 })
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                permission="batchUpdateOTB"
                icon={<ImportOutlined />}
                onClick={() => {
                  setisUploadFileShow(true)
                }}
              >
                批量更新OTB额度
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        columns={useColumns({
          onViewLogs,
          verifyCost,
          canVertifyCost: buttonCodeList.includes('vertifyCost'),
        })}
        {...tableProps}
        rowKey={(rows) => rows.id}
        isScrollY
      />
      <ImportFileModal
        loading={exportLoading}
        open={isUploadFileShow}
        onCancel={onUploadFileCancel}
        onOk={onUploadFileOk}
        form={FormUpload}
        tempCode={IMPORT_FILE_ENUM.GOODS_OTB_IMPORT}
      ></ImportFileModal>
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
